package com.mall.common.controller;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mall.b2c.util.JsonDataGridHelper;
import com.mall.common.bean.Message;
import com.mall.common.bean.Pager;
import com.mall.common.bean.SearchFilter;
import com.mall.common.bean.WebErrors;
import com.mall.common.domain.manage.Role;
import com.mall.common.domain.manage.S_userDomain;
import com.mall.common.exception.NoticeException;
import com.mall.common.service.RoleService;
import com.mall.common.service.S_userService;
import com.mall.common.util.Collections3;
import com.mall.common.util.ResponseUtils;
import com.mall.common.validation.annotation.RequiredFieldValidator;
import com.mall.common.validation.annotation.RequiredStringValidator;
import com.mall.common.validation.annotation.Validations;
import com.mall.common.web.Servlets;

/**
 * 后台Action类 - 用户
 */
@Controller
@RequestMapping("/admin/system/user")
public class UserController extends BaseController {
	
	@Resource private S_userService s_userService;
	@Resource private RoleService roleService;
	
	@RequestMapping(value="/list", method=RequestMethod.GET)
	public String list() {
		return "/admin/system/user/list";
	}
	
	@RequestMapping(value="/queryData", method=RequestMethod.POST)
	@ResponseBody
	public Pager queryData(Pager pager, HttpServletRequest request){
		Map<String, Object> filterParams = Servlets.getParametersStartingWith(request);
		List<SearchFilter> filters = SearchFilter.parse(filterParams);
		pager = s_userService.findPage(pager, filters);
		return JsonDataGridHelper.createJSONData(pager);
	}
	
	@RequestMapping(value="/add", method=RequestMethod.GET)
	public String add(Model model){
		model.addAttribute("allRoles", roleService.getAll());
		return "/admin/system/user/input";
	}
	
	@Validations(
			requiredStrings = {
					@RequiredStringValidator(fieldName="username",message="登录帐号不能为空"),
					@RequiredStringValidator(fieldName="password",message="登录密码不能为空")
			},
			requiredFields = {
					@RequiredFieldValidator(fieldName="dept.id",message="所在部门不存在"),
					@RequiredFieldValidator(fieldName="isAccountEnabled",message="是否允许登陆不能为空")
			}
	)
	@RequestMapping(value="/add", method=RequestMethod.POST)
	@ResponseBody
	public String add(S_userDomain user, String repassword, Long[] roleIds,
			HttpServletResponse response){
		if (!s_userService.isUnique("username", null, user.getUsername())) {
			throw new NoticeException("error.unique", new Object[]{"登录帐号"});
		}
		user.setRoleSet(new HashSet<Role>(roleService.get(roleIds)));
		String password = user.getPassword();
		if(StringUtils.isNotEmpty(password)){
			if(!password.equals(repassword)){
				throw new NoticeException("admin.user.save.passwordNotValid", new Object[0]);
			}
			user.setPassword(DigestUtils.md5Hex(password));
		}
		s_userService.persist(user);
		return ResponseUtils.renderJSON(successMessage, response);
	}
	
	@RequestMapping(value="/update/{id}", method=RequestMethod.GET)
	public String update(@PathVariable Long id, Model model){
		S_userDomain s_user = s_userService.find(id);
		model.addAttribute("s_user", s_user);
		model.addAttribute("allRoles", roleService.getAll());
		return "/admin/system/user/input";
	}

	@Validations(
			requiredFields = {
					@RequiredFieldValidator(fieldName="id",message="用户不存在"),
					@RequiredFieldValidator(fieldName="dept.id",message="所在部门不存在"),
					@RequiredFieldValidator(fieldName="isAccountEnabled",message="是否允许登陆不能为空")
			}
	)
	@RequestMapping(value="/update", method=RequestMethod.POST)
	public String update(S_userDomain user, Long[] roleIds, HttpServletResponse response){
		user.setRoleSet(new HashSet<Role>(roleService.get(roleIds)));
		S_userDomain persistent = s_userService.find(user.getId());
		if(persistent == null){
			throw new NoticeException("用户不存在");
		}
		if (StringUtils.isNotEmpty(user.getPassword())) {
			String passwordMd5 = DigestUtils.md5Hex(user.getPassword());
			persistent.setPassword(passwordMd5);
		}
		
		if (persistent.getIsAccountLocked() && !user.getIsAccountLocked()) {
			persistent.setLoginFailureCount(0);
			persistent.setLockedDate(null);
		} else {
			persistent.setIsAccountLocked(persistent.getIsAccountLocked());
			persistent.setLoginFailureCount(persistent.getLoginFailureCount());
			persistent.setLockedDate(persistent.getLockedDate());
		}
		s_userService.update(persistent);
		return ResponseUtils.renderJSON(persistent, response);
	}
	
	@RequestMapping(value="/delete", method=RequestMethod.POST)
	@ResponseBody
	public Message delete(Long ids) {
		s_userService.remove(ids);
		return successMessage;
	}
	
	// ajax验证当前密码是否正确
	@RequestMapping(value="/checkCurrentPassword", method=RequestMethod.POST)
	@ResponseBody
	public String checkCurrentPassword(String currentPassword, HttpServletResponse response) {
		S_userDomain admin = s_userService.loadLoginAdmin(getUserId());
		if (StringUtils.equals(DigestUtils.md5Hex(currentPassword), admin.getPassword())) {
			return ResponseUtils.renderJSON("true", response);
		} else {
			return ResponseUtils.renderJSON("false", response);
		}
	}
	
	// 更新个人资料
	@RequestMapping(value="/updateProfile", method=RequestMethod.POST)
	@ResponseBody
	public String updateProfile(String oldPassword, String currentPassword, HttpServletResponse response) {
		S_userDomain persistent = s_userService.loadLoginAdmin(getUserId());
		if(persistent == null){
			//addActionError("登录超时，请先登录!");
			return "/admin/system/common/error";
		}
		if (StringUtils.isNotEmpty(oldPassword) && StringUtils.isNotEmpty(persistent.getPassword())) {
			if (!StringUtils.equals(DigestUtils.md5Hex(oldPassword), persistent.getPassword())) {
				WebErrors errors = WebErrors.create();
				errors.addError("当前密码不正确!");
				return errors.showErrorAjax(response);
			}
		}
		persistent.setPassword(DigestUtils.md5Hex(currentPassword));
		s_userService.update(persistent);
		return ResponseUtils.renderJSON(successMessage, response);
	}
	
	// 是否已存在 ajax验证
	@RequestMapping(value="/checkUsername", method=RequestMethod.POST)
	@ResponseBody
	public String checkUsername(String username, String oldValue, HttpServletResponse response) {
		if (s_userService.isUnique("username", oldValue, username)) {
			return ResponseUtils.renderJSON("true", response);
		} else {
			return ResponseUtils.renderJSON("false", response);
		}
	}
	
	@RequestMapping(value="/addRole", method=RequestMethod.GET)
	public String addRole(){
		return "/admin/system/user/addRole";
	}
	
	@RequestMapping(value="/userRoles", method=RequestMethod.POST)
	@ResponseBody
	public Pager userRoles(Long user_id){
		S_userDomain user = s_userService.find(user_id);
		List<Role> roles = new ArrayList<Role>(user.getRoleSet());	
		return JsonDataGridHelper.createJSONData(new Pager(roles));
	}
	
	// 获取非此用户的角色
	@RequestMapping(value="/notUserRoles", method=RequestMethod.POST)
	@ResponseBody
	public Pager notUserRoles(Long user_id){
		S_userDomain user = s_userService.find(user_id);
		List<Role> roles = new ArrayList<Role>(user.getRoleSet());
		List<Role> allRoles = roleService.getAll();;
		if(Collections3.isNotEmpty(allRoles) && roles != null){
			for(Role role : roles){
				if(allRoles.contains(role)){
					allRoles.remove(role);
				}
			}
		}
		return JsonDataGridHelper.createJSONData(new Pager(allRoles));
	}
	
	@RequestMapping(value="/moveRoleLeft", method=RequestMethod.POST)
	@ResponseBody
	public String moveRoleLeft(Long user_id, Long[] roleIds, HttpServletResponse response){
		S_userDomain user = s_userService.find(user_id);
		List<Role> roles = roleService.get(roleIds);
		user.getRoleSet().addAll(roles);
		s_userService.update(user);
		return ResponseUtils.renderJSON(successMessage, response);
	}
	
	@RequestMapping(value="/moveRoleRight", method=RequestMethod.POST)
	@ResponseBody
	public String moveRoleRight(Long user_id, Long[] roleIds, HttpServletResponse response){
		S_userDomain user = s_userService.find(user_id);
		List<Role> userRoles = new ArrayList<Role>(user.getRoleSet());
		List<Role> roles = roleService.get(roleIds);
		if(Collections3.isNotEmpty(roles)){
			for(Role role : roles){
				userRoles.remove(role);
			}
		}
		user.setRoleSet(new HashSet<Role>(userRoles));
		s_userService.update(user);
		return ResponseUtils.renderJSON(successMessage, response);
	}
	
}